Categories
React Hooks

Top React Hooks — Refs, Redux, and Async

Spread the love

Hooks contains our logic code in our React app.

We can create our own hooks and use hooks provided by other people.

In this article, we’ll look at some useful React hooks.

reactive-react-redux

The reactive-react-redux library is an alternative library to React-Redux for using Redux stores in our React app.

To use it, we install it by running:

npm install reactive-react-redux

Then we can use it by writing:

import React from "react";
import { createStore } from "redux";
import { Provider, useDispatch, useTrackedState } from "reactive-react-redux";

const initialState = {
  count: 0
};

const reducer = (state = initialState, action) => {
  switch (action.type) {
    case "increment":
      return { ...state, count: state.count + 1 };
    case "decrement":
      return { ...state, count: state.count - 1 };
    case "setText":
      return { ...state, text: action.text };
    default:
      return state;
  }
};

const store = createStore(reducer);

const Counter = () => {
  const state = useTrackedState();
  const dispatch = useDispatch();
  return (
    <div>
      <span>Count: {state.count}</span>
      <button type="button" onClick={() => dispatch({ type: "increment" })}>
        increment
      </button>
      <button type="button" onClick={() => dispatch({ type: "decrement" })}>
        decrement
      </button>
    </div>
  );
};

export default function App() {
  return (
    <Provider store={store}>
      <Counter />
    </Provider>
  );
}

We have our initialState constant with the initial state.

Our reducer is a Redux reducer.

The store is created with the createStore function from Redux to create our store from the reducer .

In the Counter component, we use the useTrackedState hook to get the state.

And we use the useDispatch hook to get the dispatch function to let us dispatch our action to the reducer.

Then in App , we use the Provider with the store prop set to our store to let us use it as a data store.

Provider , useTrackedState , and useDispatch are from reactive-react-redux.

We can also select values from a state and do more.

React-async-hook

React-async-hook is a library to help us make API calls easier.

To install it, we run;

yarn add react-async-hook

or:

npm install react-async-hook --save

Then we can use it by writing:

import React from "react";
import { useAsync } from "react-async-hook";

const fetchName = async name =>
  (await fetch(`https://api.agify.io/?name=${name}`)).json();

export default function App() {
  const person = useAsync(fetchName, ["michael"]);
  return (
    <div>
      {person.loading && <div>Loading</div>}
      {person.error && <div>Error</div>}
      {person.result && (
        <div>
          <div>{JSON.stringify(person.result)}</div>
        </div>
      )}
    </div>
  );
}

We created the fetchName function to get our data.

Then we use the useAsync hook with it and the value to pass into the parameter to make the API call.

Then person has the loading , error , and result properties.

loading indicates whether the data is loading.

error indicates the error state.

result has the response body.

react-context-refs

The react-context-refs library lets us get React refs via a context.

We can install it by running:

npm i react-context-refs

Then we can use it by writing:

import React from "react";
import { useContextRef } from "react-context-refs";

const Input = ({ value, onChange, hasError }) => {
  const setRef = useContextRef({ hasError });

  return (
    <input
      style={hasError ? { backgroundColor: "orange" } : {}}
      ref={setRef}
      value={value}
      onChange={onChange}
    />
  );
};

export default function App() {
  const [val, setVal] = React.useState("");

  return (
    <div>
      <Input value={val} onChange={e => setVal(e.target.value)} hasError />
    </div>
  );
}

We pass in the hasError value to the useContextRef hook so that we can pass the returned value to the ref.

Conclusion

reactive-react-redux is an alternative for React-Redux.

React-async-hook lets us get data asynchronously.

react-context-refs lets us pass things to the ref via a context.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *